package com.fishy.chat.handler;

import cn.hutool.json.JSONUtil;
import com.fishy.chat.model.entity.Message;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@ChannelHandler.Sharable
public class WebSocketChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Resource
    private RequestMessageHandler requestMessageHandler;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) {
        String text = frame.text();
        Message message;
        try {
            message = JSONUtil.toBean(text, Message.class);
        } catch (Exception e) {
            log.error("序列化消息失败: {}", text, e);
            ctx.close();
            return;
        }
        message.setTime();
        requestMessageHandler.handle(ctx, message);
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        log.info("Client connected: {}", ctx.channel().id().asShortText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("Exception caught: {}", cause.getMessage());
    }
}